package com.wtb.javatool.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.wetoband.tool.Tool;
import com.fy.wetoband.utils.RequestUtil;
import com.wtb.javatool.common.PageBean;
import com.wtb.javatool.common.R;
import com.wtb.javatool.dto.*;
import com.wtb.javatool.entity.*;
import com.wtb.javatool.service.*;
import io.swagger.annotations.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;


@Api(tags = {"项目式教学工具相关接口"})
@Scope(SCOPE_PROTOTYPE) //务必使用多实例模式
@ComponentScan("com.wtb.javatool")
public class ProjectTeaching extends Tool {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private UserService userService;
    @Autowired
    private AssignmentService assignmentService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private LineService lineService;
    @Autowired
    private SubmissionService submissionService;
    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private ProjectClassService projectClassService;
    @Autowired
    private TeamService teamService;

    @Action
    @ApiOperation(value = "创建单个任务", httpMethod = "POST", notes = "创建单个任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "taskName", dataType = "string", value = "任务名称", required = true),
            @ApiImplicitParam(name = "taskType", dataType = "integer", value = "任务类型", required = true),
            @ApiImplicitParam(name = "createTime", dataType = "date", value = "创建时间", required = true),
            @ApiImplicitParam(name = "creatorId", dataType = "long", value = "创建人ID", required = true),
            @ApiImplicitParam(name = "taskDescription", dataType = "string", value = "任务描述"),
            @ApiImplicitParam(name = "courseId", dataType = "long", value = "课程ID"),
            @ApiImplicitParam(name = "deliverables", dataType = "Array", value = "附件"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "创建任务成功")
    })
    public R<Long> createTask(HttpServletRequest request) {
        //参数获取
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String taskName = RequestUtil.getStringParameter(request, "taskName");
        Integer taskType = RequestUtil.getIntegerParameter(request, "taskType");
        Date createTime = RequestUtil.getDateParameter(request, "createTime");
        Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
        String taskDescription = RequestUtil.getStringParameter(request, "taskDescription");
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        //生成对象
        Task task = new Task();
        task.setTaskName(taskName);
        task.setProjectId(projectId);
        task.setCreatorId(creatorId);
        task.setTaskDescription(taskDescription);
        task.setCreateTime(createTime);
        task.setTaskType(taskType);
        task.setCourseId(courseId);
        //调用服务层
        taskService.createTask(task);
        return R.success(task.getTaskId(), "创建成功");
    }

    @Action
    @ApiOperation(value = "创建项目", httpMethod = "POST", notes = "添加项目信息与相关成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectName", dataType = "string", value = "项目名称", required = true),
            @ApiImplicitParam(name = "projectDescription", dataType = "string", value = "项目描述", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "integer", value = "项目类型", required = true),
            @ApiImplicitParam(name = "creatorId", dataType = "long", value = "创建人ID", required = true),
            @ApiImplicitParam(name = "leaders", dataType = "list", value = "项目负责人ID列表", required = true),
            @ApiImplicitParam(name = "startTime", dataType = "date", value = "项目开始时间"),
            @ApiImplicitParam(name = "endTime", dataType = "date", value = "项目期限"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "创建项目成功")
    })
    public R<String> createProject(HttpServletRequest request) {
        List<Long> leaders = RequestUtil.getLongJsonArrayParameter(request, "leaders");
        Project project = new Project();
        project.setProjectName(RequestUtil.getStringParameter(request, "projectName"));
        project.setProjectDescription(RequestUtil.getStringParameter(request, "projectDescription"));
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        project.setProjectType(projectType);
        project.setCreatorId(RequestUtil.getLongParameter(request, "creatorId"));
        project.setCreateTime(RequestUtil.getDateParameter(request, "createTime"));
        project.setStartTime(RequestUtil.getDateParameter(request, "startTime"));
        project.setEndTime(RequestUtil.getDateParameter(request, "endTime"));
        projectService.createProject(project, leaders, projectType);

        return R.success("创建项目成功");
    }


    @Action
    @ApiOperation(value = "查询用户", httpMethod = "GET", notes = "根据不同属性查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户ID"),
            @ApiImplicitParam(name = "userName", dataType = "String", value = "用户名"),
            @ApiImplicitParam(name = "phone", dataType = "String", value = "手机号"),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型"),
            @ApiImplicitParam(name = "userType", dataType = "Integer", value = "用户类型"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<User>> findUser(HttpServletRequest request) {
        Long userId = RequestUtil.getLongParameter(request, "userId");
        String userName = RequestUtil.getStringParameter(request, "userName");
        String phone = RequestUtil.getStringParameter(request, "phone");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        Integer userType = RequestUtil.getIntegerParameter(request, "userType");
        List<User> users = userService.findUser(userId, userName, phone, projectType, userType);

        return R.success(users, "查询成功");
    }

    @Action
    @ApiOperation(value = "查询项目", httpMethod = "POST", notes = "根据用户ID，项目名称（可选）等来查找相关项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户ID", required = true),
            @ApiImplicitParam(name = "projectName", dataType = "String", value = "项目名称"),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型"),
            @ApiImplicitParam(name = "projectStatus", dataType = "Integer", value = "项目状态"),
            @ApiImplicitParam(name = "projectDate", dataType = "List<String>", value = "日期范围"),
            @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页总数", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<Project>> findProjects(HttpServletRequest request) {
        // 获取 projectDate 参数

        //参数获取
        Long userId = RequestUtil.getLongParameter(request, "userId");
        String projectName = RequestUtil.getStringParameter(request, "projectName");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        Integer projectStatus = RequestUtil.getIntegerParameter(request, "projectStatus");
        List<Long> projectDate = RequestUtil.getLongJsonArrayParameter(request, "projectDate");
        Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
        Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
        PageBean<Project> pageBean = projectService.findProjectsByUserId(userId, projectName, projectType, projectStatus, projectDate, currentPage, pageSize);
        return R.success(pageBean, "查询成功");
    }
//日期记录2025/3/12

    @Action
    @ApiOperation(value = "查询项目基本信息", httpMethod = "GET", notes = "根据项目ID获取项目基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "int", value = "项目类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<ProjectDto> findProjectByProjectId(HttpServletRequest request) {

        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");

        ProjectDto projectDto = projectService.findProjectByProjectId(projectId, projectType);
        return R.success(projectDto, "查询成功");
    }

    @Action
    @ApiOperation(value = "查询普通项目的所有成员", httpMethod = "GET", notes = "根据项目ID，项目名称（可选）、项目时间范围（可选获取项目所有成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "userName", dataType = "String", value = "用户名")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<UserDto>> findProjectMemberByProjectId(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String userName = RequestUtil.getStringParameter(request, "userName");
        return R.success(projectService.findProjectMemberByProjectId(projectId, userName));
    }

    @Action
    @ApiOperation(value = "查询课程项目的下的小组及其成员", httpMethod = "GET", notes = "根据项目ID，项目名称（可选）、项目时间范围（可选获取项目所有成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID"),
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<TeamDto>> findProjectTeamsAndMembersByProjectId(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Long courseId = RequestUtil.getLongParameter(request,"courseId");
        return R.success(projectService.findProjectTeamsAndMembersByProjectId(projectId,courseId));
    }

    @Action
    @ApiOperation(value = "查询项目所有任务", httpMethod = "GET",
            notes = "根据项目ID，任务名称（可选）、任务类型（可选）、所属课程ID（可选）、创建人（可选）或承担者（可选）获取项目所有相关任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "taskName", dataType = "string", value = "任务名称"),
            @ApiImplicitParam(name = "taskType", dataType = "integer", value = "任务类型"),
            @ApiImplicitParam(name = "courseId", dataType = "long", value = "所属课程ID"),
            @ApiImplicitParam(name = "creatorId", dataType = "long", value = "创建人ID"),
            @ApiImplicitParam(name = "userId", dataType = "long", value = "或承担者"),
            @ApiImplicitParam(name = "currentPage", dataType = "integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "integer", value = "每页条数", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<TaskDto>> findTasksByProjectId(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String taskName = RequestUtil.getStringParameter(request, "taskName");
        Integer taskType = RequestUtil.getIntegerParameter(request, "taskType");
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
        Long userId = RequestUtil.getLongParameter(request, "userId");
        Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
        Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
        PageBean<TaskDto> pageBean = new PageBean<>();
        if (userId != null) {
            pageBean.setRows(taskService.findMyTasksByProjectIdAndUserId(projectId, taskName, taskType, courseId, userId, currentPage, pageSize));
            pageBean.setTotalCount(taskService.countMyTasksByProjectIdAndUserId(projectId, taskName, taskType, courseId, userId));
            return R.success(pageBean, "查询成功");
        } else {
            pageBean.setRows(taskService.findTasksByProjectId(projectId, taskName, taskType, courseId, creatorId, currentPage, pageSize));
            pageBean.setTotalCount(taskService.countTasksByProjectId(projectId, taskName, taskType, courseId, creatorId));
        }

        return R.success(pageBean, "查询成功");
    }

    @Action
    @ApiOperation(value = "更新项目的成员", httpMethod = "POST",
            notes = "根据前端传输的成员列表，增删改相对应项目下的成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "userList", dataType = "string", value = "用户列表字符串", required = true),

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> upsertDeleteUsers(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String list = RequestUtil.getStringParameter(request, "userList");
        List<UserDto> userDtoList = JSONArray.parseArray(list, UserDto.class);

        projectService.upsertDeleteUsers(projectId, userDtoList);
        return R.success("更新成功");
    }

    @Action
    @ApiOperation(value = "更新项目信息", httpMethod = "POST",
            notes = "根据前端传输的项目信息，修改数据库中对应的项目实体")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID"),
            @ApiImplicitParam(name = "projectName", dataType = "string", value = "项目名称"),
            @ApiImplicitParam(name = "projectDescription", dataType = "string", value = "项目描述"),
            @ApiImplicitParam(name = "projectStatus", dataType = "integer", value = "项目状态"),
            @ApiImplicitParam(name = "startTime", dataType = "date", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", dataType = "date", value = "结束时间"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> updateProject(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String projectName = RequestUtil.getStringParameter(request, "projectName");
        String projectDescription = RequestUtil.getStringParameter(request, "projectDescription");
        Integer projectStatus = RequestUtil.getIntegerParameter(request, "projectStatus");
        Date startTime = RequestUtil.getDateParameter(request, "startTime");
        Date endTime = RequestUtil.getDateParameter(request, "endTime");
        Project project = new Project();
        project.setProjectId(projectId);
        project.setProjectName(projectName);
        project.setProjectDescription(projectDescription);
        project.setProjectStatus(projectStatus);
        project.setStartTime(startTime);
        project.setEndTime(endTime);
        projectService.updateProject(project);

        return R.success("更新成功");
    }

    @Action
    @ApiOperation(value = "查询课程", httpMethod = "GET", notes = "根据不同属性查询课程列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程号"),
            @ApiImplicitParam(name = "courseName", dataType = "string", value = "课程名"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<Course>> findCourse(HttpServletRequest request) {
        try {
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            String courseName = RequestUtil.getStringParameter(request, "courseName");
            
            System.out.println("findCourse接口被调用 - 参数：courseId=" + courseId + ", courseName=" + courseName);
            
            List<Course> courseList = courseService.findCourse(courseId, courseName);
            
            System.out.println("findCourse查询结果：找到" + (courseList != null ? courseList.size() : 0) + "条记录");
            if (courseList != null && !courseList.isEmpty()) {
                System.out.println("第一条记录：" + courseList.get(0).getCourseName());
            }
            
            return R.success(courseList, "查询成功");
        } catch (Exception e) {
            System.err.println("findCourse接口异常：" + e.getMessage());
            e.printStackTrace();
            return R.error("查询课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "更新项目关联的课程", httpMethod = "POST",
            notes = "根据前端传输的课程列表，增删相对应项目关联的课程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "courseList", dataType = "string", value = "课程列表字符串", required = true),

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> upsertDeleteCourses(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        String list = RequestUtil.getStringParameter(request, "courseList");
        List<Course> courseList = JSONArray.parseArray(list, Course.class);
        projectService.upsertDeleteCourses(projectId, courseList);
        return R.success("更新成功");
    }

    @Action
    @ApiOperation(value = "查看项目首页中，任务分配及完成情况", httpMethod = "GET",
            notes = "初步查看各任务的分配，完成等数量并返回给前端展示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "Integer", dataType = "Integer", value = "评价类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<AssignmentDto> findTaskAssignmentNumber(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Integer evaluationType = RequestUtil.getIntegerParameter(request, "evaluationType");
        AssignmentDto assignmentDto = taskService.findTaskAssignmentNumber(projectId, evaluationType);
        return R.success(assignmentDto, "查询成功");
    }

    @Action
    @ApiOperation(value = "查看任务详情", httpMethod = "GET",
            notes = "根据任务ID，返回任务详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<TaskDto> findTaskByTaskId(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        TaskDto taskDto = taskService.findTaskByTaskId(taskId, projectType);
        return R.success(taskDto, "查询成功");
    }

    @Action
    @ApiOperation(value = "为单个任务添加附件", httpMethod = "POST",
            notes = "根据任务ID，返回任务详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "file", dataType = "file", value = "文件", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> upLoadTaskAttachment(HttpServletRequest request) {
        try {
            // 获取参数
            Long taskId = RequestUtil.getLongParameter(request, "taskId");
            Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
            
            // 参数验证
            if (taskId == null || taskId <= 0) {
                return R.error("任务ID无效", 400);
            }
            
            if (creatorId == null || creatorId <= 0) {
                return R.error("创建者ID无效", 400);
            }
            
            // 创建文件上传处理器
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = upload.parseRequest(request);
            
            // 检查是否有文件
            boolean hasFile = false;
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    hasFile = true;
                    break;
                }
            }
            
            if (!hasFile) {
                return R.error("未找到上传文件", 400);
            }
            
            // 执行上传
            attachmentService.upLoadTaskAttachment(taskId, creatorId, items);
            return R.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传文件失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "删除附件", httpMethod = "POST",
            notes = "删除某个附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attachmentId", dataType = "long", value = "附件ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteAttachmentByAttachmentId(HttpServletRequest request) {
        Long attachmentId = RequestUtil.getLongParameter(request, "attachmentId");
        String attachmentUrl = RequestUtil.getStringParameter(request, "attachmentUrl");
        attachmentService.deleteAttachmentByAttachmentId(attachmentId, attachmentUrl);
        return R.success("", "删除成功");
    }

    @Action
    @ApiOperation(value = "查询某个任务的所有附件", httpMethod = "GET",
            notes = "根据任务ID，返回任务的所有附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<Attachment>> findAttachmentsByTaskId(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        List<Attachment> attachmentList = attachmentService.findAttachmentsByTaskId(taskId);

        return R.success(attachmentList, "查询成功");
    }

    @Action
    @ApiOperation(value = "更新任务名称", httpMethod = "POST",
            notes = "更新任务名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "taskName", dataType = "string", value = "任务名称", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<String> updateTaskName(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        String taskName = RequestUtil.getStringParameter(request, "taskName");
        Task task = new Task();
        task.setTaskId(taskId);
        task.setTaskName(taskName);
        taskService.updateTaskName(task);
        return R.success("更新成功", "更新成功");
    }

    @Action
    @ApiOperation(value = "更新任务描述", httpMethod = "POST",
            notes = "更新任务描述")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "taskDescription", dataType = "string", value = "任务描述")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<String> updateTaskDescription(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        String taskDescription = RequestUtil.getStringParameter(request, "taskDescription");
        Task task = new Task();
        task.setTaskId(taskId);
        task.setTaskDescription(taskDescription);
        taskService.updateTaskDescription(task);
        return R.success("更新成功", "更新成功");
    }

    @Action
    @ApiOperation(value = "更新任务类型", httpMethod = "POST",
            notes = "更新任务类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "taskType", dataType = "integer", value = "任务类型", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<String> updateTaskType(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        Integer taskType = RequestUtil.getIntegerParameter(request, "taskType");
        Task task = new Task();
        task.setTaskId(taskId);
        task.setTaskType(taskType);
        taskService.updateTaskType(task);
        return R.success("更新成功", "更新成功");
    }

    @Action
    @ApiOperation(value = "更新任务所属课程", httpMethod = "POST",
            notes = "更新任务所属课程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "long", value = "课程ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<String> updateTaskCourse(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Task task = new Task();
        task.setTaskId(taskId);
        task.setCourseId(courseId);
        taskService.updateTaskCourse(task);
        return R.success("更新成功", "更新成功");
    }

    @Action
    @ApiOperation(value = "普通项目新建任务分配记录和任务承担者", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userIdList", dataType = "list", value = "用户ID列表", required = true),
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "teamId", dataType = "long", value = "小组ID"),
            @ApiImplicitParam(name = "createTime", dataType = "date", value = "创建时间", required = true),
            @ApiImplicitParam(name = "endTime", dataType = "date", value = "截止时间", required = true),
            @ApiImplicitParam(name = "creatorId", dataType = "long", value = "创建者", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "分配成功")
    })
    public R<String> addAssignmentAndUndertaker(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        List<Long> userIdList = RequestUtil.getLongJsonArrayParameter(request, "userIdList");
        Date createTime = RequestUtil.getDateParameter(request, "createTime");
        Date endTime = RequestUtil.getDateParameter(request, "endTime");
        Assignment assignment = new Assignment();
        assignment.setTaskId(taskId);
        assignment.setTeamId(teamId);
        assignment.setCreatorId(creatorId);
        assignment.setCreateTime(createTime);
        assignment.setEndTime(endTime);
        assignmentService.addAssignmentAndUndertaker(assignment, userIdList);
        return R.success("分配成功", "分配成功");
    }

    @Action
    @ApiOperation(value = "查询某个任务的所有分配记录（不包括状态值为4（被删除）的记录，）", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "Long", value = "任务ID", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<AssignmentDto>> findAssignmentsByTaskId(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        List<AssignmentDto> assignmentDtoList = assignmentService.findAssignmentsByTaskId(taskId, projectType);
        return R.success(assignmentDtoList, "查询成功");
    }

    @Action
    @ApiOperation(value = "根据分配记录ID列表删除对应分配记录(将状态值改为4）", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assignmentIdList", dataType = "list", value = "分配记录ID列表", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 409, message = "删除失败，该记录已被分配到产线")
    })
    public R<String> deleteAssignmentByAssignmentId(HttpServletRequest request) {
        List<Long> assignmentIdList = RequestUtil.getLongJsonArrayParameter(request, "assignmentIdList");
        if (lineService.findLineAssignmentByAssignmentIds(assignmentIdList) > 0) {
            return R.error("删除失败，该记录已被分配到产线", 409);
        } else {
            assignmentService.deleteAssignmentByAssignmentId(assignmentIdList);
            return R.success("删除成功");
        }

    }

    @Action
    @ApiOperation(value = "更新单个分配记录的截至日期、承担小组", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assignmentId", dataType = "Long", value = "分配记录ID", required = true),
            @ApiImplicitParam(name = "endTime", dataType = "Date", value = "截止日期"),
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "承担小组id"),
            @ApiImplicitParam(name = "userIds", dataType = "List<Long>", value = "承担人员id列表"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> updateAssignmentEndTimeAndMember(HttpServletRequest request) {
        Long assignmentId = RequestUtil.getLongParameter(request, "assignmentId");
        Date endTime = RequestUtil.getDateParameter(request, "endTime");
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        List<Long> userIds = RequestUtil.getLongJsonArrayParameter(request, "userIds");
        Assignment assignment = new Assignment();
        assignment.setAssignmentId(assignmentId);
        assignment.setEndTime(endTime);
        assignment.setTeamId(teamId);
        assignmentService.updateAssignmentEndTimeAndTeamByAssignmentId(assignment);
        assignmentService.upsertDeleteAssignmentUndertakers(assignmentId, userIds);
        return R.success("更新成功", "更新成功");
    }

    @Action
    @ApiOperation(value = "更新多个分配记录的截止日期", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assignmentIdList", dataType = "List<Long>", value = "分配记录ID列表", required = true),
            @ApiImplicitParam(name = "endTime", dataType = "Date", value = "截止日期", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> updateAssignmentsEndTimeByAssignmentIds(HttpServletRequest request) {
        List<Long> assignmentIdList = RequestUtil.getLongJsonArrayParameter(request, "assignmentIdList");
        Date endTime = RequestUtil.getDateParameter(request, "endTime");
        assignmentService.updateAssignmentsEndTimeByAssignmentIds(assignmentIdList, endTime);
        return R.success("更新成功");
    }


    @Action
    @ApiOperation(value = "查询单个项目所有分配记录，", httpMethod = "GET",
            notes = "根据项目ID，分配记录状态（可选）、任务类型（可选）、所属课程ID（可选）获取项目所有相关分配记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "assignmentStatus", dataType = "Integer", value = "分配记录状态"),
            @ApiImplicitParam(name = "taskType", dataType = "Integer", value = "任务类型"),
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID"),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<AssignmentDto>> findAssignmentsByProjectId(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Integer assignmentStatus = RequestUtil.getIntegerParameter(request, "assignmentStatus");
        Integer taskType = RequestUtil.getIntegerParameter(request, "taskType");
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");

        List<AssignmentDto> assignmentDtoList = assignmentService.findTasksAssignments(projectId, assignmentStatus, taskType, courseId, projectType);
        return R.success(assignmentDtoList, "查询成功");
    }

    @Action
    @ApiOperation(value = "新增产线", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineName", dataType = "String", value = "产线名称", required = true),
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "createTime", dataType = "Date", value = "创建时间", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> addLine(HttpServletRequest request) {
        String lineName = RequestUtil.getStringParameter(request, "lineName");
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Date createTime = RequestUtil.getDateParameter(request, "createTime");
        lineService.addLine(lineName, projectId, createTime);
        return R.success("添加成功");
    }

    @Action
    @ApiOperation(value = "根据项目ID查询所有项目产线", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<LineDto>> findLinesByProjectId(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        List<LineDto> lines = lineService.findLinesByProjectId(projectId, projectType);
        return R.success(lines, "查询成功");
    }

    @Action
    @ApiOperation(value = "根据产线ID查询项目产线详情", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineId", dataType = "Long", value = "产线ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<LineDto> findLineByLineId(HttpServletRequest request) {
        Long lineId = RequestUtil.getLongParameter(request, "lineId");
        LineDto lineDto = lineService.findLineByLineId(lineId);
        return R.success(lineDto, "查询成功");
    }

    @Action
    @ApiOperation(value = "更新项目产线", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineId", dataType = "Long", value = "产线id", required = true),
            @ApiImplicitParam(name = "lineAssignments", dataType = "String", value = "产线节点列表字符串", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> updateLineAssignment(HttpServletRequest request) {
        Long lineId = RequestUtil.getLongParameter(request, "lineId");
        String lineAssignments = RequestUtil.getStringParameter(request, "lineAssignments");
        List<LineAssignment> lineAssignmentList = JSONArray.parseArray(lineAssignments, LineAssignment.class);
        lineService.updateLineAssignment(lineId, lineAssignmentList);
        return R.success("更新成功");
    }

    @Action
    @ApiOperation(value = "删除项目产线与其关联的记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineId", dataType = "Long", value = "产线id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteLine(HttpServletRequest request) {
        Long lineId = RequestUtil.getLongParameter(request, "lineId");
        lineService.deleteLine(lineId);
        return R.success("删除成功");
    }

    @Action
    @ApiOperation(value = "更新项目产线名称", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineId", dataType = "Long", value = "产线id", required = true),
            @ApiImplicitParam(name = "lineName", dataType = "String", value = "产线名称", required = true)

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功")
    })
    public R<String> updateLineName(HttpServletRequest request) {
        Long lineId = RequestUtil.getLongParameter(request, "lineId");
        String lineName = RequestUtil.getStringParameter(request, "lineName");
        lineService.updateLineName(lineId, lineName);
        return R.success("更新成功");
    }

    @Action
    @ApiOperation(value = "复制项目产线与产线节点", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lineId", dataType = "Long", value = "产线id", required = true),
            @ApiImplicitParam(name = "lineName", dataType = "String", value = "产线名称", required = true),
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "createTime", dataType = "Date", value = "创建时间", required = true)

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "复制成功")
    })
    public R<String> copyLine(HttpServletRequest request) {
        Long lineId = RequestUtil.getLongParameter(request, "lineId");
        String lineName = RequestUtil.getStringParameter(request, "lineName");
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        Date createTime = RequestUtil.getDateParameter(request, "createTime");
        lineService.copyLine(lineId, lineName, projectId, createTime);
        return R.success("复制成功");
    }

    @Action
    @ApiOperation(value = "查询单个或多个任务下的所有提交内容和提交文件", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tasksId", dataType = "List<Long>", value = "任务id列表", required = true),
            @ApiImplicitParam(name = "projectType", dataType = "Integer", value = "项目类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<SubmissionDto>> findSubmissionAndAchievementByTasksId(HttpServletRequest request) {
        List<Long> tasksId = RequestUtil.getLongJsonArrayParameter(request, "tasksId");
        Integer projectType = RequestUtil.getIntegerParameter(request, "projectType");
        List<SubmissionDto> submissions = taskService.findSubmissionAndAchievementByTasksId(tasksId, projectType);
        return R.success(submissions, "查询成功");
    }


    @Action
    @ApiOperation(value = "新增或修改评论记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "submissionIds", dataType = "List<Long>", value = "提交记录id列表", required = true),
            @ApiImplicitParam(name = "assignmentIds", dataType = "List<Long>", value = "分配记录id列表", required = true),
            @ApiImplicitParam(name = "score", dataType = "Double", value = "评分", required = true),
            @ApiImplicitParam(name = "comment", dataType = "String", value = "评论内容"),
            @ApiImplicitParam(name = "creatorId", dataType = "Integer", value = "评价人Id", required = true),
            @ApiImplicitParam(name = "evaluationType", dataType = "Integer", value = "评价类型", required = true),
            @ApiImplicitParam(name = "createTime", dataType = "Date", value = "创建日期", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批阅成功")
    })
    public R<String> insertOrUpdateEvaluations(HttpServletRequest request) {
        List<Long> submissionIds = RequestUtil.getLongJsonArrayParameter(request, "submissionIds");
        Double score = RequestUtil.getDoubleParameter(request, "score");
        String comment = RequestUtil.getStringParameter(request, "comment");
        Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
        Integer evaluationType = RequestUtil.getIntegerParameter(request, "evaluationType");
        Date createTime = RequestUtil.getDateParameter(request, "createTime");

        evaluationService.insertOrUpdateEvaluations(submissionIds, score, comment, creatorId, createTime, evaluationType);
        return R.success("", "批阅成功");
    }

    @Action
    @ApiOperation(value = "退回（删除）提交记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "submissionIds", dataType = "List<Long>", value = "提交记录id列表", required = true),
            @ApiImplicitParam(name = "assignmentIds", dataType = "List<Long>", value = "分配记录id列表", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteSubmissions(HttpServletRequest request) {
        List<Long> submissionIds = RequestUtil.getLongJsonArrayParameter(request, "submissionIds");
        List<Long> assignmentIds = RequestUtil.getLongJsonArrayParameter(request, "assignmentIds");


        assignmentService.updateAssignmentStatusByAssignmentId(assignmentIds, 1);
        submissionService.deleteSubmissions(submissionIds);
        return R.success("", "删除成功");
    }

    @Action
    @ApiOperation(value = "查询教师用户拥有的课程", httpMethod = "get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户id", required = true),
            @ApiImplicitParam(name = "courseName", dataType = "String", value = "课程名称"),
            @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页个数", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<CourseDto>> findCoursesByUserId(HttpServletRequest request) {
        try {
            Long userId = RequestUtil.getLongParameter(request, "userId");
            String courseName = RequestUtil.getStringParameter(request, "courseName");
            Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
            Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
            
            System.out.println("findCoursesByUserId接口被调用 - 参数：userId=" + userId + 
                              ", courseName=" + courseName + 
                              ", currentPage=" + currentPage + 
                              ", pageSize=" + pageSize);
            
            PageBean<CourseDto> pageCourses = courseService.findCoursesByUserId(userId, courseName, currentPage, pageSize);
            
            System.out.println("findCoursesByUserId查询结果：总记录数=" + pageCourses.getTotalCount() + 
                              ", 当前页记录数=" + (pageCourses.getRows() != null ? pageCourses.getRows().size() : 0));
            
            return R.success(pageCourses, "查询成功");
        } catch (Exception e) {
            System.err.println("findCoursesByUserId接口异常：" + e.getMessage());
            e.printStackTrace();
            return R.error("查询用户课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "查询单个课程的详情信息", httpMethod = "get")
    public R<List<Course>> findCourseDetails(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        List<Course> courseList = courseService.findCourse(courseId, null);
        return R.success(courseList, "查询成功");
    }

    @Action
    @ApiOperation(value = "查询课程的关联任务的分配记录情况", httpMethod = "get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程id", required = true),
            @ApiImplicitParam(name = "evaluationType", dataType = "Integer", value = "评价类型", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<AssignmentDto> findTaskAssignmentNumberByCourseId(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Integer evaluationType = RequestUtil.getIntegerParameter(request, "evaluationType");
        AssignmentDto assignmentDto = assignmentService.findTaskAssignmentNumberByCourseId(courseId, evaluationType);
        return R.success(assignmentDto, "查询成功");
    }

    @Action
    @ApiOperation(value = "获取课程所有班级，小组和学生", httpMethod = "get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功")
    })
    public R<List<ClassDto>> findProjectClassesAndTeamsByCourseId(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        List<ClassDto> courseDtos = projectClassService.findProjectClassesAndTeamsByCourseId(courseId);
        return R.success(courseDtos, "获取成功");
    }

    @Action
    @ApiOperation(value = "新增项目班并与课程关联", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程id", required = true),
            @ApiImplicitParam(name = "classNAme", dataType = "String", value = "班级名称", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> addProjectClass(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        String className = RequestUtil.getStringParameter(request, "className");
        projectClassService.addProjectClass(courseId, className);
        return R.success("", "添加成功");
    }

    @Action
    @ApiOperation(value = "删除班级", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteProjectClass(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        projectClassService.deleteProjectClass(classId);
        return R.success("", "删除成功");
    }

    @Action
    @ApiOperation(value = "获取单个班级的学生", httpMethod = "get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组id"),
            @ApiImplicitParam(name = "studentId", dataType = "Long", value = "学号"),
            @ApiImplicitParam(name = "haveTeam", dataType = "Integer", value = " 判断是否有小组"),
            @ApiImplicitParam(name = "userName", dataType = "String", value = "学生名称"),
            @ApiImplicitParam(name = "studentNo", dataType = "String", value = "学号"),
            @ApiImplicitParam(name = "college", dataType = "String", value = "学院"),
            @ApiImplicitParam(name = "major", dataType = "String", value = "专业"),
            @ApiImplicitParam(name = "className", dataType = "String", value = "班级"),
            @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页总数", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<UserDto>> findClassStudents(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        Long studentId = RequestUtil.getLongParameter(request, "studentId");
        String userName = RequestUtil.getStringParameter(request, "userName");
        Integer haveTeam = RequestUtil.getIntegerParameter(request, "haveTeam");
        Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
        Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
        String studentNo = RequestUtil.getStringParameter(request, "studentNo");
        String college = RequestUtil.getStringParameter(request, "college");
        String major = RequestUtil.getStringParameter(request, "major");
        String className = RequestUtil.getStringParameter(request, "className");

        PageBean<UserDto> userDtoPageBean = userService.findClassStudents(classId, teamId, studentId, userName, haveTeam, currentPage, pageSize, studentNo, college, major, className);
        return R.success(userDtoPageBean, "查询成功");
    }

    @Action
    @ApiOperation(value = "新增小组，并关联到班级", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
            @ApiImplicitParam(name = "teamName", dataType = "String", value = "小组名称", required = true),

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> addTeam(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        String teamName = RequestUtil.getStringParameter(request, "teamName");
        
        System.out.println("收到添加小组请求: classId=" + classId + ", teamName=" + teamName);
        
        if (classId == null) {
            System.err.println("添加小组失败: 班级ID不能为空");
            return R.error("班级ID不能为空", 400);
        }
        
        if (teamName == null || teamName.trim().isEmpty()) {
            System.err.println("添加小组失败: 小组名称不能为空");
            return R.error("小组名称不能为空", 400);
        }
        
        try {
            teamService.addTeam(classId, teamName);
            System.out.println("成功添加小组: " + teamName + " 到班级ID: " + classId);
            return R.success("", "添加小组成功");
        } catch (Exception e) {
            System.err.println("添加小组失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("添加小组失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "删除小组", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "移除成功")
    })
    public R<String> deleteTeam(HttpServletRequest request) {
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        System.out.println("接收到删除小组请求, teamId=" + teamId);
        
        if (teamId == null) {
            System.err.println("删除小组失败: 参数teamId为空");
            return R.error("小组ID不能为空", 400);
        }
        
        try {
            teamService.deleteTeam(teamId);
            System.out.println("成功删除小组ID: " + teamId);
            return R.success("", "成功删除小组");
        } catch (Exception e) {
            System.err.println("删除小组失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("删除小组失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "设置小组组长", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组id", required = true),
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "设置成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "设置失败")
    })
    public R<String> setTeamLeader(HttpServletRequest request) {
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        Long userId = RequestUtil.getLongParameter(request, "userId");
        
        System.out.println("收到设置小组组长请求: teamId=" + teamId + ", userId=" + userId);
        
        if (teamId == null) {
            System.err.println("设置组长失败: 小组ID不能为空");
            return R.error("小组ID不能为空", 400);
        }
        
        if (userId == null) {
            System.err.println("设置组长失败: 用户ID不能为空");
            return R.error("用户ID不能为空", 400);
        }
        
        try {
            // 检查用户是否在小组中
            List<UserDto> teamMembers = teamService.findStudentsByTeamId(teamId);
            boolean isUserInTeam = false;
            
            if (teamMembers != null) {
                for (UserDto member : teamMembers) {
                    if (member.getUserId() != null && member.getUserId().equals(userId)) {
                        isUserInTeam = true;
                        break;
                    }
                }
            }
            
            if (!isUserInTeam) {
                System.err.println("设置组长失败: 用户ID=" + userId + " 不在小组ID=" + teamId + "中");
                return R.error("只能将小组内的成员设为组长", 400);
            }
            
            teamService.updateTeamLeader(teamId, userId);
            System.out.println("成功设置小组组长: 小组ID=" + teamId + ", 用户ID=" + userId);
            return R.success("", "设置组长成功");
        } catch (Exception e) {
            System.err.println("设置小组组长失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("设置组长失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "为项目班添加学生", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
            @ApiImplicitParam(name = "studentIds", dataType = "List<Long>", value = "学生id列表", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> addClassStudentRef(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        List<Long> studentIds = RequestUtil.getLongJsonArrayParameter(request, "studentIds");
        
        System.out.println("调用addClassStudentRef方法: classId=" + classId + ", studentIds=" + 
            (studentIds != null ? studentIds : "null") + ", 数量=" + 
            (studentIds != null ? studentIds.size() : 0));
        
        if (classId == null) {
            System.err.println("班级ID不能为空");
            return R.error("班级ID不能为空", 400);
        }
        
        if (studentIds == null || studentIds.isEmpty()) {
            System.err.println("学生ID列表不能为空");
            return R.error("学生ID列表不能为空", 400);
        }
        
        try {
            projectClassService.insertClassStudentRef(classId, studentIds);
            System.out.println("成功添加" + studentIds.size() + "名学生到班级" + classId);
            return R.success("", "添加成功");
        } catch (Exception e) {
            System.err.println("添加学生到班级失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("添加学生失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "为项目班删除学生", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
            @ApiImplicitParam(name = "studentIds", dataType = "List<Long>", value = "学生id列表", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteClassStudentRef(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        List<Long> studentIds = RequestUtil.getLongJsonArrayParameter(request, "studentIds");
        projectClassService.deleteClassStudentRef(classId, studentIds);
        return R.success("", "删除成功");
    }

    @Action
    @ApiOperation(value = "查询工具内所有学生", httpMethod = "get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id"),
            @ApiImplicitParam(name = "studentId", dataType = "List<Long>", value = "学生学号"),
            @ApiImplicitParam(name = "studentName", dataType = "List<Long>", value = "学生名称"),
            @ApiImplicitParam(name = "studentNo", dataType = "String", value = "学号"),
            @ApiImplicitParam(name = "college", dataType = "String", value = "学院"),
            @ApiImplicitParam(name = "major", dataType = "String", value = "专业"),
            @ApiImplicitParam(name = "className", dataType = "String", value = "班级"),
            @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页总数", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<Student>> findAllStudents(HttpServletRequest request) {
        Long studentId = RequestUtil.getLongParameter(request, "studentId");
        String studentName = RequestUtil.getStringParameter(request, "studentName");
        Long classId = RequestUtil.getLongParameter(request, "classId");
        Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
        Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
        String studentNo = RequestUtil.getStringParameter(request, "studentNo");
        String college = RequestUtil.getStringParameter(request, "college");
        String major = RequestUtil.getStringParameter(request, "major");
        String className = RequestUtil.getStringParameter(request, "className");
        
        System.out.println("调用findAllStudents方法: classId=" + classId + ", studentName=" + studentName + 
            ", studentNo=" + studentNo + ", college=" + college + ", major=" + major + ", className=" + className);
        
        try {
            PageBean<Student> pageBean = userService.findAllStudents(classId, studentId, studentName, currentPage, pageSize, studentNo, college, major, className);
            System.out.println("findAllStudents查询结果: 总数=" + pageBean.getTotalCount() + ", 返回行数=" + 
                (pageBean.getRows() != null ? pageBean.getRows().size() : 0));
                
            if (pageBean.getRows() != null && !pageBean.getRows().isEmpty()) {
                Student firstStudent = pageBean.getRows().get(0);
                System.out.println("第一个学生信息: id=" + firstStudent.getStudentId() + ", name=" + firstStudent.getStudentName());
            }
                
            return R.success(pageBean, "查询成功");
        } catch (Exception e) {
            System.err.println("findAllStudents异常: " + e.getMessage());
            e.printStackTrace();
            return R.error("查询学生失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "删除项目", httpMethod = "POST", notes = "根据项目ID删除项目及其关联的所有数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功")
    })
    public R<String> deleteProject(HttpServletRequest request) {
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        projectService.deleteProject(projectId);
        return R.success("删除项目成功");
    }

    @Action
    @ApiOperation(value = "获取课程列表", httpMethod = "GET", notes = "获取所有课程列表，用于下拉框等场景")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功")
    })
    public R<List<Course>> getCourseList(HttpServletRequest request) {
        try {
            // 获取所有课程列表
            List<Course> courses = courseService.findAllCourses();
            
            // 返回课程列表，确保包含所有需要的字段
            return R.success(courses, "获取课程列表成功");
        } catch (Exception e) {
            System.err.println("获取课程列表失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("获取课程列表失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "删除任务", httpMethod = "DELETE", notes = "根据任务ID删除任务及其相关数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "long", value = "任务ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 404, message = "任务不存在"),
            @ApiResponse(code = 500, message = "删除失败")
    })
    public R<String> deleteTask(HttpServletRequest request) {
        Long taskId = RequestUtil.getLongParameter(request, "taskId");
        
        if (taskId == null) {
            System.out.println("删除任务失败: 参数taskId为空");
            return R.error("任务ID不能为空", 400);
        }
        
        System.out.println("接收到删除任务请求, taskId=" + taskId);
        
        try {
            boolean success = taskService.deleteTask(taskId);
            if (success) {
                System.out.println("删除任务成功, taskId=" + taskId);
                return R.success("删除任务成功");
            } else {
                // 尝试查询任务是否存在
                try {
                    TaskDto task = taskService.findTaskByTaskId(taskId, null);
                    if (task == null) {
                        System.out.println("删除任务失败: 任务不存在, taskId=" + taskId);
                        return R.error("删除任务失败：任务不存在", 404);
                    } else {
                        System.out.println("删除任务失败: 数据库操作异常, taskId=" + taskId);
                        return R.error("删除任务失败：数据库操作异常", 500);
                    }
                } catch (Exception e) {
                    System.out.println("删除任务失败: 查询任务状态时发生异常, taskId=" + taskId + ", " + e.getMessage());
                    e.printStackTrace();
                    return R.error("删除任务失败：系统异常", 500);
                }
            }
        } catch (Exception e) {
            System.out.println("删除任务失败: 异常信息, taskId=" + taskId + ", " + e.getMessage());
            e.printStackTrace();
            return R.error("删除任务失败：" + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "创建课程", httpMethod = "POST", notes = "创建新课程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseData", dataType = "String", value = "课程数据JSON字符串", required = true),
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "创建者用户ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "创建成功")
    })
    public R<Long> createCourse(HttpServletRequest request) {
        try {
            // 获取参数
            String courseDataStr = RequestUtil.getStringParameter(request, "courseData");
            Long userId = RequestUtil.getLongParameter(request, "userId");
            
            if (courseDataStr == null || courseDataStr.isEmpty()) {
                return R.error("课程数据不能为空", 400);
            }
            
            // 解析课程数据
            Course course = new Course();
            JSONObject jsonObject = JSON.parseObject(courseDataStr);
            
            String courseName = jsonObject.getString("course_name");
            if (courseName == null) courseName = jsonObject.getString("courseName");
            course.setCourseName(courseName);
            
            String courseDescription = jsonObject.getString("course_description");
            if (courseDescription == null) courseDescription = jsonObject.getString("courseDescription");
            course.setCourseDescription(courseDescription);
            
            Integer courseStatus = jsonObject.getInteger("course_status");
            if (courseStatus == null) courseStatus = jsonObject.getInteger("courseStatus");
            course.setCourseStatus(courseStatus != null ? courseStatus : 0);
            
            // 处理项目列表
            List<Long> projectIds = new ArrayList<>();
            JSONArray projectsArray = jsonObject.getJSONArray("projects");
            if (projectsArray != null && !projectsArray.isEmpty()) {
                for (int i = 0; i < projectsArray.size(); i++) {
                    JSONObject projectObj = projectsArray.getJSONObject(i);
                    if (projectObj != null && projectObj.getLong("projectId") != null) {
                        projectIds.add(projectObj.getLong("projectId"));
                    }
                }
            }
            
            // 创建课程
            Long courseId = courseService.createCourse(course, userId, projectIds);
            
            if (courseId != null && courseId > 0) {
                return R.success(courseId, "创建课程成功");
            } else {
                return R.error("创建课程失败", 500);
            }
        } catch (IllegalArgumentException e) {
            return R.error(e.getMessage(), 400);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("创建课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "更新课程", httpMethod = "POST", notes = "更新课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseData", dataType = "String", value = "课程数据JSON字符串", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "更新失败")
    })
    public R<String> updateCourse(HttpServletRequest request) {
        try {
            // 获取参数
            String courseDataStr = RequestUtil.getStringParameter(request, "courseData");
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            
            if (courseDataStr == null || courseDataStr.isEmpty()) {
                return R.error("课程数据不能为空", 400);
            }
            
            if (courseId == null || courseId <= 0) {
                return R.error("课程ID无效", 400);
            }
            
            // 解析课程数据
            Course course = new Course();
            course.setCourseId(courseId);
            
            JSONObject jsonObject = JSON.parseObject(courseDataStr);
            
            String courseName = jsonObject.getString("course_name");
            if (courseName == null) courseName = jsonObject.getString("courseName");
            course.setCourseName(courseName);
            
            String courseDescription = jsonObject.getString("course_description");
            if (courseDescription == null) courseDescription = jsonObject.getString("courseDescription");
            course.setCourseDescription(courseDescription);
            
            Integer courseStatus = jsonObject.getInteger("course_status");
            if (courseStatus == null) courseStatus = jsonObject.getInteger("courseStatus");
            if (courseStatus != null) {
                course.setCourseStatus(courseStatus);
            }
            
            // 处理项目列表
            List<Long> projectIds = new ArrayList<>();
            JSONArray projectsArray = jsonObject.getJSONArray("projects");
            if (projectsArray != null && !projectsArray.isEmpty()) {
                for (int i = 0; i < projectsArray.size(); i++) {
                    JSONObject projectObj = projectsArray.getJSONObject(i);
                    if (projectObj != null && projectObj.getLong("projectId") != null) {
                        projectIds.add(projectObj.getLong("projectId"));
                    }
                }
            }
            
            // 更新课程
            boolean result = courseService.updateCourse(course, projectIds);
            
            if (result) {
                return R.success("更新课程成功");
            } else {
                return R.error("更新课程失败", 500);
            }
        } catch (IllegalArgumentException e) {
            return R.error(e.getMessage(), 400);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("更新课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "删除课程", httpMethod = "POST", notes = "删除课程及相关关联数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "删除失败")
    })
    public R<String> deleteCourse(HttpServletRequest request) {
        try {
            // 日志记录请求内容
            System.out.println("删除课程 - 请求开始");
            
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            
            // 记录接收到的参数
            System.out.println("删除课程 - 参数: courseId=" + courseId);
            
            if (courseId == null) {
                System.out.println("删除课程失败: 课程ID为空");
                return R.error("课程ID不能为空", 400);
            }
            
            // 调用服务删除课程
            boolean success = courseService.deleteCourse(courseId);
            
            if (success) {
                System.out.println("删除课程 - 成功: courseId=" + courseId);
                return R.success("删除课程成功");
            } else {
                System.out.println("删除课程 - 失败: courseId=" + courseId);
                return R.error("删除课程失败", 500);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("删除课程 - 异常: " + e.getMessage());
            return R.error("删除课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "更新课程状态", httpMethod = "POST", notes = "更新课程状态（未开课、进行中、已结课）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true),
            @ApiImplicitParam(name = "courseStatus", dataType = "Integer", value = "课程状态", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "更新失败")
    })
    public R<String> updateCourseStatus(HttpServletRequest request) {
        try {
            // 日志记录请求内容
            System.out.println("更新课程状态 - 请求开始");
            
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            Integer courseStatus = RequestUtil.getIntegerParameter(request, "courseStatus");
            
            // 记录接收到的参数
            System.out.println("更新课程状态 - 参数: courseId=" + courseId + ", courseStatus=" + courseStatus);
            
            if (courseId == null) {
                System.out.println("更新课程状态失败: 课程ID为空");
                return R.error("课程ID不能为空", 400);
            }
            
            if (courseStatus == null || courseStatus < 0 || courseStatus > 2) {
                System.out.println("更新课程状态失败: 课程状态无效");
                return R.error("课程状态无效", 400);
            }
            
            // 查找课程
            List<Course> courses = courseService.findCourse(courseId, null);
            if (courses == null || courses.isEmpty()) {
                System.out.println("更新课程状态失败: 课程不存在");
                return R.error("课程不存在", 404);
            }
            
            Course course = courses.get(0);
            course.setCourseStatus(courseStatus);
            
            // 调用服务更新课程
            boolean success = courseService.updateCourse(course, null);
            
            if (success) {
                System.out.println("更新课程状态 - 成功: courseId=" + courseId);
                return R.success("更新课程状态成功");
            } else {
                System.out.println("更新课程状态 - 失败: courseId=" + courseId);
                return R.error("更新课程状态失败", 500);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("更新课程状态 - 异常: " + e.getMessage());
            return R.error("更新课程状态失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "批量更新课程状态", httpMethod = "POST", notes = "批量更新多个课程的状态（未开课、进行中、已结课）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseIds", dataType = "String", value = "课程ID列表的JSON字符串", required = true),
            @ApiImplicitParam(name = "courseStatus", dataType = "Integer", value = "要设置的课程状态", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量更新成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "批量更新失败")
    })
    public R<String> batchUpdateCourseStatus(HttpServletRequest request) {
        try {
            // 日志记录请求内容
            System.out.println("批量更新课程状态 - 请求开始");
            
            String courseIdsStr = RequestUtil.getStringParameter(request, "courseIds");
            Integer courseStatus = RequestUtil.getIntegerParameter(request, "courseStatus");
            
            // 记录接收到的参数
            System.out.println("批量更新课程状态 - 参数: courseIds=" + courseIdsStr + ", courseStatus=" + courseStatus);
            
            if (courseIdsStr == null || courseIdsStr.trim().isEmpty()) {
                System.out.println("批量更新课程状态失败: 课程ID列表为空");
                return R.error("课程ID列表不能为空", 400);
            }
            
            if (courseStatus == null || courseStatus < 0 || courseStatus > 2) {
                System.out.println("批量更新课程状态失败: 课程状态无效");
                return R.error("课程状态无效", 400);
            }
            
            // 解析课程ID列表
            List<Long> courseIds = new ArrayList<>();
            try {
                JSONArray courseArray = JSON.parseArray(courseIdsStr);
                for (int i = 0; i < courseArray.size(); i++) {
                    Long id = courseArray.getLong(i);
                    if (id != null) {
                        courseIds.add(id);
                    }
                }
            } catch (Exception e) {
                System.out.println("批量更新课程状态失败: 解析课程ID列表失败 - " + e.getMessage());
                return R.error("课程ID列表格式不正确", 400);
            }
            
            if (courseIds.isEmpty()) {
                System.out.println("批量更新课程状态失败: 解析后课程ID列表为空");
                return R.error("课程ID列表不能为空", 400);
            }
            
            // 批量更新课程状态
            int successCount = 0;
            List<Long> failedIds = new ArrayList<>();
            
            for (Long courseId : courseIds) {
                try {
                    // 查找课程
                    List<Course> courses = courseService.findCourse(courseId, null);
                    if (courses == null || courses.isEmpty()) {
                        failedIds.add(courseId);
                        continue;
                    }
                    
                    Course course = courses.get(0);
                    course.setCourseStatus(courseStatus);
                    
                    // 调用服务更新课程
                    boolean success = courseService.updateCourse(course, null);
                    if (success) {
                        successCount++;
                    } else {
                        failedIds.add(courseId);
                    }
                } catch (Exception e) {
                    System.out.println("更新课程状态失败: courseId=" + courseId + " - " + e.getMessage());
                    failedIds.add(courseId);
                }
            }
            
            if (failedIds.isEmpty()) {
                System.out.println("批量更新课程状态 - 全部成功: 更新了" + successCount + "个课程");
                return R.success("成功更新" + successCount + "个课程的状态");
            } else {
                System.out.println("批量更新课程状态 - 部分成功: 更新了" + successCount + "个课程，失败" + failedIds.size() + "个");
                return R.success("成功更新" + successCount + "个课程的状态，失败" + failedIds.size() + "个");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("批量更新课程状态 - 异常: " + e.getMessage());
            return R.error("批量更新课程状态失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "批量删除课程", httpMethod = "POST", notes = "批量删除多个课程及其关联数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseIds", dataType = "String", value = "课程ID列表的JSON字符串", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量删除成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "批量删除失败")
    })
    public R<String> batchDeleteCourses(HttpServletRequest request) {
        try {
            // 日志记录请求内容
            System.out.println("批量删除课程 - 请求开始");
            
            String courseIdsStr = RequestUtil.getStringParameter(request, "courseIds");
            
            // 记录接收到的参数
            System.out.println("批量删除课程 - 参数: courseIds=" + courseIdsStr);
            
            if (courseIdsStr == null || courseIdsStr.trim().isEmpty()) {
                System.out.println("批量删除课程失败: 课程ID列表为空");
                return R.error("课程ID列表不能为空", 400);
            }
            
            // 解析课程ID列表
            List<Long> courseIds = new ArrayList<>();
            try {
                JSONArray courseArray = JSON.parseArray(courseIdsStr);
                for (int i = 0; i < courseArray.size(); i++) {
                    Long id = courseArray.getLong(i);
                    if (id != null) {
                        courseIds.add(id);
                    }
                }
            } catch (Exception e) {
                System.out.println("批量删除课程失败: 解析课程ID列表失败 - " + e.getMessage());
                return R.error("课程ID列表格式不正确", 400);
            }
            
            if (courseIds.isEmpty()) {
                System.out.println("批量删除课程失败: 解析后课程ID列表为空");
                return R.error("课程ID列表不能为空", 400);
            }
            
            // 批量删除课程
            int successCount = 0;
            List<Long> failedIds = new ArrayList<>();
            
            for (Long courseId : courseIds) {
                try {
                    // 调用服务删除课程
                    boolean success = courseService.deleteCourse(courseId);
                    if (success) {
                        successCount++;
                    } else {
                        failedIds.add(courseId);
                    }
                } catch (Exception e) {
                    System.out.println("删除课程失败: courseId=" + courseId + " - " + e.getMessage());
                    failedIds.add(courseId);
                }
            }
            
            if (failedIds.isEmpty()) {
                System.out.println("批量删除课程 - 全部成功: 删除了" + successCount + "个课程");
                return R.success("成功删除" + successCount + "个课程");
            } else {
                System.out.println("批量删除课程 - 部分成功: 删除了" + successCount + "个课程，失败" + failedIds.size() + "个");
                return R.success("成功删除" + successCount + "个课程，失败" + failedIds.size() + "个");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("批量删除课程 - 异常: " + e.getMessage());
            return R.error("批量删除课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "添加项目到课程", httpMethod = "POST",
            notes = "向课程中添加关联项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "long", value = "课程ID", required = true),
            @ApiImplicitParam(name = "projectIds", dataType = "string", value = "项目ID列表的JSON字符串", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加成功")
    })
    public R<String> addProjectsToCourse(HttpServletRequest request) {
        try {
            // 获取参数
            String projectIdsStr = RequestUtil.getStringParameter(request, "projectIds");
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            
            if (courseId == null) {
                return R.error("课程ID不能为空", 400);
            }
            
            if (projectIdsStr == null || projectIdsStr.trim().isEmpty()) {
                return R.error("项目ID列表不能为空", 400);
            }
            
            // 解析项目ID列表
            List<Long> projectIds = new ArrayList<>();
            try {
                JSONArray projectArray = JSON.parseArray(projectIdsStr);
                for (int i = 0; i < projectArray.size(); i++) {
                    Long projectId = projectArray.getLong(i);
                    if (projectId != null) {
                        projectIds.add(projectId);
                    }
                }
            } catch (Exception e) {
                return R.error("项目ID列表格式不正确", 400);
            }
            
            if (projectIds.isEmpty()) {
                return R.error("项目ID列表不能为空", 400);
            }
            
            // 查找课程是否存在
            List<Course> courses = courseService.findCourse(courseId, null);
            if (courses == null || courses.isEmpty()) {
                return R.error("课程不存在", 404);
            }
            
            // 删除旧的关联关系，添加新的
            Course course = courses.get(0);
            boolean success = courseService.updateCourse(course, projectIds);
            
            if (success) {
                return R.success("添加项目到课程成功");
            } else {
                return R.error("添加项目到课程失败", 500);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加项目到课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "获取课程成绩数据", httpMethod = "GET", notes = "获取课程学生成绩数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true),
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级ID"),
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组ID"),
            @ApiImplicitParam(name = "studentName", dataType = "String", value = "学生姓名或学号"),
            @ApiImplicitParam(name = "studentMajor", dataType = "String", value = "学生专业"),
            @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页条数", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功")
    })
    public R<PageBean<StudentGradeDto>> getCourseGrades(HttpServletRequest request) {
        try {
            // 获取参数
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            Long classId = RequestUtil.getLongParameter(request, "classId");
            Long teamId = RequestUtil.getLongParameter(request, "teamId");
            String studentName = RequestUtil.getStringParameter(request, "studentName");
            String studentMajor = RequestUtil.getStringParameter(request, "studentMajor");
            Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
            Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");
            
            if (courseId == null) {
                return R.error("课程ID不能为空", 400);
            }
            
            // 调用服务获取成绩数据
            PageBean<StudentGradeDto> pageBean = assignmentService.findCourseGrades(
                courseId, classId, teamId, studentName, studentMajor, currentPage, pageSize);
            
            return R.success(pageBean, "获取成绩数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取成绩数据失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "导出课程成绩数据", httpMethod = "GET", notes = "导出课程学生成绩数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "导出成功")
    })
    public R<String> exportCourseGrades(HttpServletRequest request) {
        try {
            // 获取参数
            Long courseId = RequestUtil.getLongParameter(request, "courseId");
            
            if (courseId == null) {
                return R.error("课程ID不能为空", 400);
            }
            
            // 调用服务导出成绩数据
            String fileUrl = assignmentService.exportCourseGrades(courseId);
            
            return R.success(fileUrl, "导出成绩数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导出成绩数据失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "根据小组ID查询小组成员", httpMethod = "GET", notes = "根据小组ID获取该小组的所有学生成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功")
    })
    public R<List<UserDto>> findStudentsByTeamId(HttpServletRequest request) {
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        List<UserDto> students = teamService.findStudentsByTeamId(teamId);
        return R.success(students, "查询成功");
    }

    @Action
    @ApiOperation(value = "创建项目提醒", httpMethod = "POST", notes = "创建项目提醒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true),
            @ApiImplicitParam(name = "taskIds", dataType = "String", value = "任务ID列表的JSON字符串", required = true),
            @ApiImplicitParam(name = "userIds", dataType = "String", value = "用户ID列表的JSON字符串", required = true),
            @ApiImplicitParam(name = "remindType", dataType = "String", value = "提醒类型", required = true),
            @ApiImplicitParam(name = "message", dataType = "String", value = "提醒消息", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "创建成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "创建失败")
    })
    public R<String> createRemind(HttpServletRequest request) {
        try {
            // 获取参数
            Long projectId = RequestUtil.getLongParameter(request, "projectId");
            String taskIdsJson = RequestUtil.getStringParameter(request, "taskIds");
            String userIdsJson = RequestUtil.getStringParameter(request, "userIds");
            String remindType = RequestUtil.getStringParameter(request, "remindType");
            String message = RequestUtil.getStringParameter(request, "message");
            
            // 参数验证
            if (projectId == null || taskIdsJson == null || userIdsJson == null || remindType == null || message == null) {
                return R.error("参数不能为空", 400);
            }
            
            List<Long> taskIds = JSON.parseArray(taskIdsJson, Long.class);
            List<Long> userIds = JSON.parseArray(userIdsJson, Long.class);
            
            if (taskIds.isEmpty() || userIds.isEmpty()) {
                return R.error("任务列表和用户列表不能为空", 400);
            }
            
            // TODO: 实际项目中需要添加创建提醒的业务逻辑
            // reminderService.createReminder(projectId, taskIds, userIds, remindType, message);
            
            return R.success("创建提醒成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("创建提醒失败: " + e.getMessage(), 500);
        }
    }
    
    @Action
    @ApiOperation(value = "获取项目提醒列表", httpMethod = "GET", notes = "获取项目的所有提醒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "获取失败")
    })
    public R<List<Object>> getRemindList(HttpServletRequest request) {
        try {
            Long projectId = RequestUtil.getLongParameter(request, "projectId");
            
            if (projectId == null) {
                return R.error("项目ID不能为空", 400);
            }
            
            // TODO: 实际项目中需要添加获取提醒列表的业务逻辑
            // List<Reminder> reminders = reminderService.getReminders(projectId);
            
            // 模拟数据
            List<Object> reminders = new ArrayList<>();
            
            return R.success(reminders, "获取提醒列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取提醒列表失败: " + e.getMessage(), 500);
        }
    }
    
    @Action
    @ApiOperation(value = "删除项目提醒", httpMethod = "POST", notes = "删除指定的项目提醒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "remindId", dataType = "Long", value = "提醒ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "删除失败")
    })
    public R<String> deleteRemind(HttpServletRequest request) {
        try {
            Long remindId = RequestUtil.getLongParameter(request, "remindId");
            
            if (remindId == null) {
                return R.error("提醒ID不能为空", 400);
            }
            
            // TODO: 实际项目中需要添加删除提醒的业务逻辑
            // reminderService.deleteReminder(remindId);
            
            return R.success("删除提醒成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("删除提醒失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "关联用户到所有课程", httpMethod = "get", notes = "将指定用户关联到所有课程，以便在'我的课程'中显示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "关联成功")
    })
    public R<String> linkUserToAllCourses(HttpServletRequest request) {
        try {
            Long userId = RequestUtil.getLongParameter(request, "userId");
            if (userId == null) {
                return R.error("用户ID不能为空", 400);
            }
            
            System.out.println("linkUserToAllCourses接口被调用 - 参数：userId=" + userId);
            
            // 1. 获取所有课程
            List<Course> allCourses = courseService.findAllCourses();
            if (allCourses == null || allCourses.isEmpty()) {
                return R.success("没有可关联的课程", "操作完成");
            }
            
            System.out.println("找到 " + allCourses.size() + " 个课程需要关联");
            
            // 2. 为每个课程添加与用户的关联
            int successCount = 0;
            for (Course course : allCourses) {
                try {
                    // 查询是否已经存在关联
                    boolean exists = courseService.checkCourseTeacherRefExists(course.getCourseId(), userId);
                    if (!exists) {
                        courseService.insertCourseTeacherRef(course.getCourseId(), userId);
                        successCount++;
                    }
                } catch (Exception e) {
                    System.err.println("关联课程 " + course.getCourseId() + " 到用户 " + userId + " 失败: " + e.getMessage());
                }
            }
            
            return R.success("成功关联 " + successCount + " 个课程到用户", "关联成功");
        } catch (Exception e) {
            System.err.println("linkUserToAllCourses接口异常：" + e.getMessage());
            e.printStackTrace();
            return R.error("关联用户到课程失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "查询课程关联的项目", httpMethod = "GET", notes = "获取课程关联的所有项目")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true),
        @ApiImplicitParam(name = "projectName", dataType = "String", value = "项目名称（可选，用于过滤）"),
        @ApiImplicitParam(name = "projectStatus", dataType = "Integer", value = "项目状态（可选，用于过滤）"),
        @ApiImplicitParam(name = "currentPage", dataType = "Integer", value = "当前页数", required = true),
        @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页条数", required = true)
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功")
    })
    public R<PageBean<Project>> findCourseProjects(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        String projectName = RequestUtil.getStringParameter(request, "projectName");
        Integer projectStatus = RequestUtil.getIntegerParameter(request, "projectStatus");
        Integer currentPage = RequestUtil.getIntegerParameter(request, "currentPage");
        Integer pageSize = RequestUtil.getIntegerParameter(request, "pageSize");

        if (courseId == null) {
            return R.error("课程ID不能为空", 400);
        }

        try {
            PageBean<Project> projects = projectService.findProjectsByCourseId(
                courseId, projectName, projectStatus, currentPage, pageSize);
            return R.success(projects, "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "从课程移除项目", httpMethod = "POST", notes = "从课程中移除关联项目")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true),
        @ApiImplicitParam(name = "projectId", dataType = "Long", value = "项目ID", required = true)
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "移除成功")
    })
    public R<String> removeCourseProject(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Long projectId = RequestUtil.getLongParameter(request, "projectId");
        
        if (courseId == null || projectId == null) {
            return R.error("参数不完整，课程ID和项目ID都不能为空", 400);
        }
        
        try {
            projectService.removeProjectFromCourse(courseId, projectId);
            return R.success("成功从课程移除项目");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("移除项目失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "获取可添加到课程的项目列表", httpMethod = "GET", notes = "获取可以添加到课程的项目列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "courseId", dataType = "Long", value = "课程ID", required = true),
        @ApiImplicitParam(name = "userId", dataType = "Long", value = "用户ID", required = true)
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功")
    })
    public R<List<Project>> getAvailableProjects(HttpServletRequest request) {
        Long courseId = RequestUtil.getLongParameter(request, "courseId");
        Long userId = RequestUtil.getLongParameter(request, "userId");
        
        if (courseId == null) {
            return R.error("课程ID不能为空", 400);
        }
        if (userId == null) {
            return R.error("用户ID不能为空", 400);
        }
        
        try {
            List<Project> availableProjects = projectService.getAvailableProjectsForCourse(userId, courseId);
            return R.success(availableProjects, "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取可添加项目列表失败: " + e.getMessage(), 500);
        }
    }

    @Action
    @ApiOperation(value = "批量修改学生所在小组", httpMethod = "post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", dataType = "Long", value = "班级id", required = true),
            @ApiImplicitParam(name = "teamId", dataType = "Long", value = "小组id", required = true),
            @ApiImplicitParam(name = "studentIds", dataType = "List<Long>", value = "学生id列表", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "修改失败")
    })
    public R<String> setTeamForStudents(HttpServletRequest request) {
        Long classId = RequestUtil.getLongParameter(request, "classId");
        Long teamId = RequestUtil.getLongParameter(request, "teamId");
        List<Long> studentIds = RequestUtil.getLongJsonArrayParameter(request, "studentIds");
        
        System.out.println("收到批量修改学生所在小组请求: classId=" + classId + ", teamId=" + teamId + 
            ", studentIds=" + (studentIds != null ? studentIds : "null") + ", 学生数量=" + 
            (studentIds != null ? studentIds.size() : 0));
        
        if (classId == null) {
            System.err.println("修改学生所在小组失败: 班级ID不能为空");
            return R.error("班级ID不能为空", 400);
        }
        
        if (teamId == null) {
            System.err.println("修改学生所在小组失败: 小组ID不能为空");
            return R.error("小组ID不能为空", 400);
        }
        
        if (studentIds == null || studentIds.isEmpty()) {
            System.err.println("修改学生所在小组失败: 学生ID列表不能为空");
            return R.error("学生ID列表不能为空", 400);
        }
        
        try {
            userService.setTeamForStudents(classId, teamId, studentIds);
            System.out.println("成功将" + studentIds.size() + "名学生添加到小组ID: " + teamId);
            return R.success("", "成功将学生添加到小组");
        } catch (Exception e) {
            System.err.println("修改学生所在小组失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("修改学生所在小组失败: " + e.getMessage(), 500);
        }
    }
}

